package org.gthelper.handler;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.gthelper.data.DataGeter;
import org.gthelper.database.FileInfo;
import org.gthelper.error.ErrorCode;
import org.gthelper.order.OrderInfo;
//import org.gthelper.testtools.Printer;


public class DirGeter extends Handler
{

	@Override
	public int handle(OrderInfo orderinfo) {
		// TODO 自动生成的方法存根
		//get id
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataGeter dg = new DataGeter();
		int errcode=dg.getData(orderinfo.orderStream, baos);
		if(errcode!=ErrorCode.NORMAL)return errcode;
		byte[] userid = baos.toByteArray();
		baos.reset();
		String usrid="";
		try {
			usrid = new String(userid,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return ErrorCode.UNKNOWN;
		}
		
		//get filelist
		ArrayList<FileInfo> filelist=null;
		try {
			 filelist = FileInfo.getfilelist_allbyuserID(usrid);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return ErrorCode.DATABASEERR;
		}
		
		//向用户返回
		DataOutputStream dos = new DataOutputStream(orderinfo.mainOutput);
		String filestring="";
		int fileCount = filelist.size();
		FileInfo tmp;
		for(int i=0;i<fileCount;++i)
		{
			tmp = filelist.get(i);
			if(tmp.getstatus()<0)continue;
			filestring = filestring
					+tmp.getfilename()+","
					+tmp.getsplit_num_x()+","
					+tmp.getsplit_num_y()+","
					+tmp.getsplit_size()+","
					+tmp.getresidule();
			if(i<(fileCount-1))filestring=filestring+"&";
		}
//		Printer.print("@DirGeter-dirStr", filestring);
		byte[] ret = null;
		try {
			 ret = filestring.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return ErrorCode.UNKNOWN;
		}
		
		//return to user
		try {
			dos.writeLong(ret.length);
			dos.write(ret);
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return ErrorCode.UNKNOWN;
		}
		
		
		return ErrorCode.NORMAL;
	}
	
}